﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using Dropthings.Widget.Widgets;
using Dropthings.Widget.Framework;

public partial class Widgets_RefreshWidget : System.Web.UI.UserControl, IWidget
{
    private IWidgetHost _Host;

    private XElement _State;
    private XElement State
    {
        get
        {
            string state = this._Host.GetState();
            if (string.IsNullOrEmpty(state))
                state = "<state><args></args></state>";
            if (_State == null) _State = XElement.Parse(state);
            return _State;
        }

    }


    public string Args
    {
        get { return (State.Element("args") ?? new XElement("args", "")).Value; }
        set { State.Element("args").Value = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    void IWidget.Init(IWidgetHost host)
    {
        this._Host = host;
    }

    void IWidget.ShowSettings()
    {
        ArgsTextBox.Text = this.Args;

        SettingsPanel.Visible = true;
    }
    void IWidget.HideSettings()
    {
        SettingsPanel.Visible = false;
    }
    void IWidget.Minimized()
    {
    }
    void IWidget.Maximized()
    {
    }
    void IWidget.Closed()
    {
    }

    private void SaveState()
    {
        var xml = this.State.Xml();
        this._Host.SaveState(xml);
    }

    protected void SaveSettings_Clicked(object sender, EventArgs e)
    {
        this.Args = ArgsTextBox.Text;   
        
        this.SaveState();
    }

    protected void Refresher_Click(object sender, EventArgs e)
    {
        string strPushedArg = string.Empty;
        if (ArgsTextBox.Text != string.Empty)
        {
            string strCatTextbox = ArgsTextBox.Text;
            
            StringWriter writer = new StringWriter();
            Server.HtmlDecode(strCatTextbox, writer);
            strPushedArg = writer.ToString();
            Session["Refresher"] = strPushedArg;
            Args = strPushedArg;
            this.State.Add(new XCData(Args));
            this.SaveState();
        }
        
        Page.Response.Redirect(Page.Request.Url.ToString(), true);
    }
}
